package com.dt.zbcy.provider.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.dt.zbcy.provider.common.enums.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class HttpUtil {

	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

	public static HttpServletRequest getHttpServletRequest(ServletRequest request) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		return httpRequest;
	}

	public static HttpServletResponse getHttpServletRequest(ServletResponse response) {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		return httpResponse;
	}

	public static void toHttpErrorResponse(ServletRequest request, ServletResponse response, int status, String code,
                                           String msg) {
		try {
			HttpServletResponse httpResponse = getHttpServletRequest(response);
			httpResponse.setCharacterEncoding("UTF-8");
			httpResponse.setContentType("application/json");
			httpResponse.setHeader("Access-Control-Allow-Origin", "*");
            //HTTP响应头，指定服务器允许进行跨域资源访问的"请求方法"列表，一般用在响应预检请求上
			httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            //HTTP响应头，指定服务器允许进行跨域资源访问的"请求头"列表，一般用在响应预检请求上
			httpResponse.setHeader("Access-Control-Allow-Headers","x-auth-token,Origin, X-Requested-With, Content-Type, Accept");  
            //HTTP响应头，凡是浏览器请求中携带了身份信息，而响应头中没有返回Access-Control-Allow-Credentials: true的，
            //浏览器都会忽略此次响应
			httpResponse.setHeader("Access-Control-Allow-Credentials", "false");
			httpResponse.setStatus(status);

			Map<String, Object> errorMap = new HashMap<String, Object>();
			errorMap.put("code", code);
			errorMap.put("msg", msg);
			errorMap.put("success", false);
			httpResponse.getWriter().write(JSONObject.toJSONString(errorMap));
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	public static void toHttpSuccessResponse(ServletRequest request, ServletResponse response, int status, String code,
                                             Map<String,Object> message) {
		try {
			HttpServletResponse httpResponse = getHttpServletRequest(response);
			httpResponse.setCharacterEncoding("UTF-8");
			httpResponse.setContentType("application/json");
			httpResponse.setStatus(status);

			Map<String, Object> errorMap = new HashMap<String, Object>();
			errorMap.put("code", code);
			errorMap.put("msg", message);
			errorMap.put("success", true);
			errorMap.put("serverTime", new Date());
			httpResponse.getWriter().write(JSONObject.toJSONString(errorMap));
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	/**
	 * 检查是否是异步请求
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isAxaxRequest(ServletRequest request) {
		HttpServletRequest httpRequest = getHttpServletRequest(request);
		String requestType = httpRequest.getHeader(Constants.PARAM_HEADER_XREQUESTEDWITH);
		if (null != requestType && requestType.equals(Constants.PARAM_HEADER_XREQUESTEDWITH)) {
			return true;
		}
		return false;
	}

	public static String getHeader(ServletRequest request, String key) {
		HttpServletRequest httpRequest = getHttpServletRequest(request);
		String value = httpRequest.getHeader(key);
		return value;
	}

	public static String getParameter(ServletRequest request, String key) {
		HttpServletRequest httpRequest = getHttpServletRequest(request);
		String value = httpRequest.getParameter(key);
		return value;
	}

	public static String getStringValue(ServletRequest request, String key) {
		String value = null;
		if (parameterIsNotEmpty(request, key)) {
			value = getParameter(request, key);
		} else if (headerIsNotEmpty(request, key)) {
			value = getHeader(request, key);
		}
		return value;
	}

	public static Integer getIntegerValue(ServletRequest request, String key) {
		String value = getStringValue(request, key);
		return value == null ? 0 : Integer.parseInt(value);
	}

	public static Long getLongValue(ServletRequest request, String key) {
		String value = getStringValue(request, key);
		return value == null ? null : Long.parseLong(value);
	}

	public static boolean parameterIsNotEmpty(ServletRequest request, String key) {
		String value = getParameter(request, key);
		if (StringUtils.isNotEmpty(value)) {
			return true;
		}
		return false;
	}

	public static boolean headerIsNotEmpty(ServletRequest request, String key) {
		String value = getHeader(request, key);
		if (StringUtils.isNotEmpty(value) ) {
			return true;
		}
		return false;
	}
}
